<template>
  <div class="add">
    <DetailsFrom :bool="bool" @addFn="addFn" @backFn="backFn" @backIndex="backIndex">
      <template #top>
        <div class="step">
          <div class="head">
            <div style="flex:1;">
              <div style="display:flex; align-items: center;">
                <div class="text" :class="!firstShow?'is-success':''">1</div>
                <div class="line" :class="!firstShow?'is-success-line':''" />
              </div>
              <div class="main" :class="!firstShow?'is-success':''">基础信息</div>
            </div>
            <div class="text2">
              <div class="text" :class="!firstShow?'is-success2':''">2</div>
              <div class="main main2" :class="!firstShow?'is-success2':''">分配库位</div>
            </div>
          </div>
        </div>
      </template>
      <template>
        <!-- 表单 -->
        <div v-if="firstShow">
          <el-form ref="addForm" :model="addForm" label-position="top" :rules="addFormRules">
            <el-row>
              <el-col :span="6">
                <el-form-item label="货主编号" prop="code">
                  <el-input v-model="addForm.code" :disabled="true" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="货主名称" prop="name">
                  <el-input v-model="addForm.name" placeholder="请输入" clearable />

                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系人" prop="personName">
                  <el-input v-model="addForm.personName" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系人电话" prop="phone">
                  <el-input v-model="addForm.phone" placeholder="请输入" clearable />

                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系人邮箱" prop="email">
                  <el-input v-model="addForm.email" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="省/市/区" prop="location">
                  <el-cascader
                    v-model="addForm.location"
                    size="large"
                    :options="options"
                    :props="{ expandTrigger: 'hover' }"
                    clearable
                    @change="handleChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="address">
                  <el-input v-model="addForm.address" clearable placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入内容" resize="none" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- 列表 -->
        <div v-else>
          <!-- 如果有 -->
          <div v-if="locationList.length">
            <StepForm ref="selTable" :table-data="locationList" :table-col="tableCol" :current="current" :size="size">
              <template #btn>
                <div class="tableInfo">
                  <el-button class="add importantButton" @click="dialogOpen">分配库位
                  </el-button>
                  <el-button class="add minorImportantButton" style="background: #f8f5f5;" @click="delAll">取消分配
                  </el-button>
                </div>
              </template>
              <template #edit="props">
                <el-button
                  type="text"
                  size="small"
                  @click="delOwnerLocation(props.status)"
                >取消分配</el-button>
              </template>
            </StepForm>
            <MyPage :total-page="totalPage" @changeSize="changeSize" @changeCurrent="changeCurrent" />
          </div>
          <div v-else class="empty">
            111
          </div>
        </div>
      </template>
    </DetailsFrom>
    <!-- 弹窗 -->
    <el-dialog title="分配货主库位" :visible.sync="visible">
      <el-form ref="form" :model="form">
        <el-form-item>
          <el-cascader
            v-model="form.idStrArray"
            :options="options1"
            :props="props"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="minorImportantButton unimportanceButton" @click="visible = false">取 消</el-button>
        <el-button class="minorImportantButton " type="primary" @click="yesAdd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { myTree, messageFn } from '@/utils/myutils'
import { regionData, CodeToText } from 'element-china-area-data'
import { nextFn, searchOwner, addOwner, editOwner, warehouseList, areaTree, batchOwner, ownerLocation, delOwnerLocation } from '@/api'
import DetailsFrom from '@/components/DetailsFrom'
import StepForm from '@/components/StepTable'
import MyPage from '@/components/MyPage'
export default {
  components: { DetailsFrom, StepForm, MyPage },
  data() {
    return {
      options: regionData,
      addForm: {},
      addFormRules: {
        phone: [
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, trigger: 'blur', message: '请输入正确手机号' },
          { required: true, message: '请输入联系人手机号', trigger: 'blur' }],
        code: [
          { required: true }
        ],
        name: [
          { required: true, message: '请输入请输入货主名称', trigger: 'blur' }
        ],
        personName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请选择区域', trigger: 'blur' }
        ],
        email: [{ pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, trigger: 'blur', message: '请输入正确手机号' }]
      },
      firstShow: true,
      locationList: [],
      tableCol: [
        { prop: 'warehouseName', label: '仓库名称' },
        { prop: 'areaName', label: '库区名称' },
        { prop: 'locationCode', label: '库位编号' },
        { prop: 'locationName', label: '库位名称' }
      ],
      totalPage: null,
      size: 10,
      current: 1,
      visible: false,
      props: { multiple: true },
      options1: [],
      ownerinfo: {},
      form: {},
      bool: true
    }
  },
  // 组件路由首位 修改meta的名字
  beforeRouteEnter(to, from, next) {
    if (to.params.id === 'null') {
      to.meta.title = '新增货主'
    } else {
      to.meta.title = '编辑货主'
    }
    next()
  },
  async created() {
    if (this.$route.params.id === 'null') {
      const res = await nextFn('HZ')
      this.$set(this.addForm, 'code', res.data.data)
      this.$set(this.addForm, 'status', 0)
      this.$forceUpdate()
    } else {
      const res = await searchOwner(this.$route.params.id)
      this.addForm = res.data.data
      this.addForm.location = [this.addForm.province, this.addForm.city, this.addForm.area]
    }
  },
  methods: {
    // 新增货主
    addFn() {
      this.$refs.addForm.validate(async(valid) => {
        if (!valid) return
        if (this.addForm.id) {
          // 修改
          console.log(this.addForm.id)
          await editOwner(this.addForm).then(async() => {
            this.$message.success('恭喜你！修改成功')
            this.firstShow = false
            this.bool = false
            await this.ownerFn(this.addForm.id)
          })
        } else {
          // 新增
          this.addForm.location = CodeToText[this.addForm.location[0]] +
        '/' +
        CodeToText[this.addForm.location[1]] +
        '/' +
        CodeToText[this.addForm.location[2]]
          await addOwner(this.addForm).then(async res => {
            if (res.data.data) {
              this.ownerinfo = res.data.data
              this.$message.success('恭喜你！新增成功')
              this.firstShow = false
              this.bool = false
              await this.ownerFn({ ownerId: this.ownerinfo.id })
            } else {
              this.$message.warning(`${res.data.msg}`)
            }
          })
        }
      })
    },
    // 表格请求
    async ownerFn(ownerId) {
      const res1 = await ownerLocation({
        ownerId,
        current: this.current,
        size: this.size
      })
      this.locationList = res1.data.data.records
      this.totalPage = Number(res1.data.data.total)
    },
    handleChange(val) {
      const obj = {}
      obj.province = val[0]
      obj.city = val[1]
      obj.area = val[2]
      this.addForm = Object.assign(this.addForm, obj)
    },
    // 改变页数
    async changeSize(val) {
      this.size = val
      if (this.addForm.id) {
        await this.ownerFn(this.addForm.id)
      } else {
        await this.ownerFn({ ownerId: this.ownerinfo.id })
      }
    },
    async changeCurrent(val) {
      if (this.addForm.id) {
        await this.ownerFn(this.addForm.id)
      } else {
        await this.ownerFn({ ownerId: this.ownerinfo.id })
      }
    },
    // 确定分配
    async yesAdd() {
      let res
      if (this.ownerinfo.id) {
        res = await batchOwner({ idStrArray: [], ownerId: this.ownerinfo.id })
        this.visible = false
      } else {
        res = await batchOwner({ idStrArray: [], ownerId: this.addForm.id })
        this.visible = false
      }
      messageFn(res.data.isSuccess, '分配')
    },
    // 分配弹窗
    async dialogOpen() {
      const res = await warehouseList({ status: 1 })
      const list = await Promise.all(res.data.data.map(async(item) => await areaTree({ '仓库id': item.id })))
      const arr = res.data.data.map((item, i) => {
        return {
          label: item.name,
          value: item.id,
          children: list[i].data.data
        }
      })
      // 递归添加不能选择的属性
      myTree(arr)
      this.options1 = arr
      this.visible = true
    },
    // 取消分配
    delOwnerLocation(val) {
      console.log(val)
      this.$confirm(`确认取消货主的库位：${val.locationName} 吗？, 是否继续?`, '取消分配确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delOwnerLocation(`ids[]=${val.id}`)
        await this.ownerFn()
        this.$message({
          type: 'success',
          message: '取消分配成功!'
        })
      })
    },
    // 返回上一页
    backFn() {
      this.firstShow = true
    },
    // 返回管理
    backIndex() {
      this.$router.push({ name: 'goods-owner' })
    },
    // 取消分配函数
    async delOwner(str) {
      await delOwnerLocation(str)
    },
    // 多选取消
    async delAll() {
      const str = this.$refs.selTable.selArr.map(item => {
        return `ids[]=${item.id}`
      }).join('&')
      await delOwnerLocation(str)
      await this.ownerFn()
      this.$message({
        type: 'success',
        message: '取消分配成功!'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/my-form.scss';
@import '@/styles/common.scss';

.step {
  width: 600px;
  margin: 0 auto;
  height: 100px;
  margin-top: 56px;

  .head {
    color: #303133;
    border-color: #303133;
    position: relative;
    width: 100%;
    display: flex;
    justify-content: space-between;
    height: 57px;

    .line {
      // border-color: inherit;
      background-color: #c0c4cc;
      flex: 1;
      height: 2px;
    }

    .text {
      border-radius: 50%;
      border: 2px solid;
      position: relative;
      z-index: 1;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 24px;
      height: 24px;
      font-size: 14px;
      box-sizing: border-box;
      background: #fff;
      transition: .15s ease-out;
      text-align: center;
      font-weight: 700;
    }

    .text2 {
      color: #c0c4cc;
      border-color: #c0c4cc;
    }

    .main {
      margin-top: 10px;
      font-weight: 700;
      color: #303133;
    }

    .main2 {
      color: #c0c4cc;
    }
  }
}
.tableInfo{
  padding: 20px 30px;
}
.dialog-footer{
  display: flex !important;
  justify-content: end !important;
}
.is-success{
 color:#ffb200 !important;
 border-color:#ffb200 !important;
}
.is-success2{
 color:#303133 !important;
 border-color:#303133 !important;
}
.is-success-line{
 background-color:#ffb200 !important;

}
.empty{
  border-top: 1px solid #f5efee;
    padding: 100px 0;
    margin: 0 auto;
    color: #b5abab;
    font-size: 14px;
}
</style>
